using System;
using Aspects;
using PostSharp.CodeModel;
using PostSharp.Laos.Weaver;

namespace Weaver
{
   /// <summary>
   /// This weaver adds an attribute to a property.
   /// </summary>
   public class PropertyAttributeWeaver : TypeLevelAspectWeaver
   {
      #region Constructors

      public PropertyAttributeWeaver(string propertyName, string associationName)
      {
         PropertyName = propertyName;
         AssociationName = associationName;
      }

      #endregion

      #region Fields

      public readonly string AssociationName;
      public readonly string PropertyName;

      #endregion

      #region Methods

      /// <summary>
      /// Adds an <see cref="AssociationAttribute"/> to a property.
      /// </summary>
      public override void Implement()
      {
         // Create a new attribute using our helper function.
         var attribute = Utils.CreateAssociationAttribute(Task.Project.Module, AssociationName);
         
         // Then get the named property and add the attribute to it!
         var property = GetLinkProperty();
         property.CustomAttributes.Add(attribute);
      }

      #endregion

      #region Properties

      /// <summary>
      /// The gets the property.
      /// </summary>
      private PropertyDeclaration GetLinkProperty()
      {
         foreach (var property in ((TypeDefDeclaration) TargetType).Properties)
         {
            if (property.Name == PropertyName)
            {
               return property;
            }
         }
         throw new Exception(string.Format("Could not find property of name {0}", PropertyName));
      }

      #endregion
   }
}